<template>
  <div class="order-detail-container">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    <div v-else-if="!order" class="error-container">
      <el-empty description="未找到订单信息" />
      <el-button type="primary" @click="$router.push('/orders')">返回订单列表</el-button>
    </div>
    <div v-else class="order-detail">
      <div class="order-header">
<!--        <h2>订单详情</h2>-->
        <div class="order-actions">
          <el-button
            v-if="order.status === 1"
            type="primary"
            size="small"
            @click="payOrder"
          >
            立即支付
          </el-button>
          <el-button
            v-if="order.status === 2"
            type="success"
            size="small"
            @click="confirmReceived"
          >
            确认收货
          </el-button>
<!--          <el-button-->
<!--            type="info"-->
<!--            size="small"-->
<!--            @click="printOrder"-->
<!--          >-->
<!--            打印订单-->
<!--          </el-button>-->
        </div>
      </div>

      <el-card class="order-info-card">
        <div class="order-status">
          <el-tag :type="getStatusType(order.status)">
            {{ order.status}}
          </el-tag>
        </div>

        <div class="order-info">
          <div class="info-item">
            <span class="label">订单编号：</span>
            <span class="value">{{ order.orderNo }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ order.createTime }}</span>
          </div>
          <div v-if="order.payTime" class="info-item">
            <span class="label">支付时间：</span>
            <span class="value">{{ order.payTime }}</span>
          </div>
          <div v-if="order.completeTime" class="info-item">
            <span class="label">完成时间：</span>
            <span class="value">{{ order.completeTime }}</span>
          </div>
        </div>
      </el-card>

      <el-card class="product-card">
        <div class="product-info">
          <div class="product-image">
            <img :src="order.productImage || defaultImage" alt="商品图片">
          </div>
          <div class="product-details">
            <h3>{{ order.productName }}</h3>
            <div class="price-info">
              <span class="price">￥{{ order.totalAmount }}</span>
              <span class="quantity">x {{ order.quantity || 1 }}</span>
            </div>
          </div>
        </div>
      </el-card>

      <el-card class="payment-card">
        <div class="payment-info">
          <div class="info-item">
            <span class="label">支付方式：</span>
            <span class="value">{{ order.paymentMethod || '在线支付' }}</span>
          </div>
          <div class="info-item total">
            <span class="label">订单总额：</span>
            <span class="value price">￥{{ order.totalAmount }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 支付对话框 -->
    <el-dialog
      title="请选择支付方式"
      :visible.sync="paymentVisible"
      width="400px"
      center
      @close="closePaymentDialog"
    >
      <div class="payment-dialog-content">
        <div class="payment-methods">
          <div
            class="payment-method-item"
            :class="{ active: paymentMethod === 'balance' }"
            @click="changePaymentMethod('balance')"
          >
            <i class="el-icon-wallet"></i>
            <span>账户余额</span>
          </div>
          <div
            class="payment-method-item"
            :class="{ active: paymentMethod === 'wechat' }"
            @click="changePaymentMethod('wechat')"
          >
            <i class="el-icon-s-platform"></i>
            <span>微信支付</span>
          </div>
          <div
            class="payment-method-item"
            :class="{ active: paymentMethod === 'alipay' }"
            @click="changePaymentMethod('alipay')"
          >
            <i class="el-icon-s-finance"></i>
            <span>支付宝支付</span>
          </div>
        </div>

        <div v-if="paymentMethod === 'balance'" class="balance-payment-container">
          <div class="balance-info">
            <span class="label">账户余额：</span>
            <span class="value price">￥{{ userBalance || '加载中...' }}</span>
          </div>
          <div class="balance-info">
            <span class="label">订单金额：</span>
            <span class="value price">￥{{ order.totalAmount }}</span>
          </div>
          <el-button
            type="primary"
            @click="handleBalancePayment"
            :disabled="!userBalance || userBalance < order.totalAmount"
            style="width: 100%; margin-top: 20px;"
          >
            {{ userBalance && userBalance < order.totalAmount ? '余额不足' : '确认支付' }}
          </el-button>
        </div>

        <div v-else class="qr-code-container">
          <div v-if="loadingQRCode" class="qr-code-loading">
            <el-skeleton :rows="5" animated />
          </div>
          <template v-else>
            <img :src="qrCodeUrl" alt="支付二维码" class="qr-code" v-if="qrCodeUrl">
            <div class="qr-code-tip">请使用{{ paymentMethod === 'wechat' ? '微信' : '支付宝' }}扫码支付</div>
          </template>
        </div>

        <!-- 模拟支付按钮（仅用于演示） -->
        <el-button type="success" @click="mockPaymentSuccess" style="width: 100%; margin-top: 20px;">
          模拟支付成功
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrders, payOrder, confirmReceived, getPaymentQRCode, balancePayment, checkPaymentStatus } from '@/api/huacai/orders';

export default {
  name: 'OrderDetail',
  data() {
    return {
      loading: false,
      order: null,
      defaultImage: require("@/assets/logo/logo.png"), // 使用已存在的图片
      paymentVisible: false,
      paymentMethod: 'balance', // 默认支付方式：balance, wechat 或 alipay
      qrCodeUrl: '', // 支付二维码URL
      loadingQRCode: false, // 二维码加载状态
      userBalance: 1000, // 模拟用户余额，实际应从用户信息API获取
      paymentStatusTimer: null, // 用于轮询支付状态
    };
  },
  created() {
    this.fetchOrderDetail();
  },
  methods: {
    // 获取订单详情
    async fetchOrderDetail() {
      this.loading = true;
      try {
        const orderId = this.$route.params.orderId || this.$route.query.orderId;
        if (!orderId) {
          this.$message.error('订单ID不能为空');
          return;
        }

        const response = await getOrders(orderId);
        if (response.code === 200) {
          this.order = response.data;
        } else {
          this.$message.error(response.message || '获取订单详情失败');
        }
      } catch (error) {
        console.error('获取订单详情出错:', error);
        this.$message.error('获取订单详情失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '已取消',
        1: '待支付',
        2: '已支付',
        3: '已完成'
      };
      return statusMap[status] || '未知状态';
    },

    // 获取状态类型
    getStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'primary',
        3: 'success'
      };
      return typeMap[status] || 'info';
    },

    // 支付订单
    payOrder() {
      this.paymentVisible = true;
      // 模拟获取支付二维码
      this.generatePaymentQRCode();
    },

    // 生成支付二维码
    async generatePaymentQRCode() {
      if (this.paymentMethod === 'balance') {
        return; // 账户余额支付不需要二维码
      }

      this.loadingQRCode = true;
      this.qrCodeUrl = '';

      try {
        // 调用后端API获取真实的支付二维码
        const response = await getPaymentQRCode(this.order.orderNo, this.paymentMethod);
        if (response.code === 200 && response.data) {
          this.qrCodeUrl = response.data.qrCodeUrl;
          // 开始轮询支付状态
          this.startPaymentStatusPolling();
        } else {
          // 如果API调用失败，使用模拟数据
          const mockQRCodes = {
            wechat: 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=wechat_pay_mock_' + this.order.orderNo,
            alipay: 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=alipay_mock_' + this.order.orderNo
          };
          this.qrCodeUrl = mockQRCodes[this.paymentMethod];
          this.$message.warning('获取支付二维码失败，使用模拟数据');
        }
      } catch (error) {
        console.error('获取支付二维码出错:', error);
        // 使用模拟数据作为备用
        const mockQRCodes = {
          wechat: 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=wechat_pay_mock_' + this.order.orderNo,
          alipay: 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=alipay_mock_' + this.order.orderNo
        };
        this.qrCodeUrl = mockQRCodes[this.paymentMethod];
        this.$message.error('获取支付二维码失败，请稍后重试');
      } finally {
        this.loadingQRCode = false;
      }
    },

    // 切换支付方式
    changePaymentMethod(method) {
      this.paymentMethod = method;
        if (method !== 'balance') {
        this.generatePaymentQRCode();
      }
    },

    // 关闭支付对话框
    closePaymentDialog() {
      this.paymentVisible = false;
      this.qrCodeUrl = '';
      this.clearPaymentStatusPolling(); // 清除支付状态轮询
    },

    // 处理账户余额支付
    async handleBalancePayment() {
      try {
        // 检查余额是否足够
        if (this.userBalance < this.order.totalAmount) {
          this.$message.error('账户余额不足，请选择其他支付方式');
          return;
        }

        // 调用余额支付API
        const response = await balancePayment(this.order.orderNo);
        if (response.code === 200) {
          // 支付成功
          this.paymentVisible = false;
          this.$message.success('支付成功');
          // 更新用户余额（实际应用中应该重新获取用户信息）
          this.userBalance -= this.order.totalAmount;
          // 刷新订单详情
          await this.fetchOrderDetail();
        } else {
          this.$message.error(response.message || '支付失败');
        }
      } catch (error) {
        console.error('余额支付出错:', error);
        this.$message.error('支付过程中出现错误，请稍后重试');
      }
    },

    // 开始轮询支付状态
    startPaymentStatusPolling() {
      // 清除可能存在的定时器
      this.clearPaymentStatusPolling();

      // 设置新的定时器，每3秒检查一次支付状态
      this.paymentStatusTimer = setInterval(async () => {
        try {
          const response = await checkPaymentStatus(this.order.orderNo);
          if (response.code === 200) {
            // 如果支付成功
            if (response.data && response.data.isPaid) {
              // 清除定时器
              this.clearPaymentStatusPolling();
              // 关闭支付对话框
              this.paymentVisible = false;
              this.$message.success('支付成功');
              // 刷新订单详情
              await this.fetchOrderDetail();
            }
          }
        } catch (error) {
          console.error('检查支付状态出错:', error);
        }
      }, 3000);
    },

    // 清除支付状态轮询
    clearPaymentStatusPolling() {
      if (this.paymentStatusTimer) {
        clearInterval(this.paymentStatusTimer);
        this.paymentStatusTimer = null;
      }
    },

    // 处理支付
    async mockPaymentSuccess() {
      try {
        const response = await payOrder(this.order.orderNo);
        if (response.code === 200) {
          this.paymentVisible = false;
          this.$message.success('支付成功');
          // 刷新订单详情
          await this.fetchOrderDetail();
        } else {
          this.$message.error(response.message || '支付失败');
        }
      } catch (error) {
        console.error('支付出错:', error);
        this.$message.error('支付过程中出现错误，请稍后重试');
      }
    },

    // 确认收货
    async confirmReceived() {
      try {
        // 这里应该调用后端API确认收货
        // 现在我们使用模拟数据
        this.$confirm('确认已收到商品吗?', '确认收货', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message.success('确认收货成功');
          // 模拟更新订单状态
          this.order.status = 3; // 已完成
          this.order.completeTime = new Date().toLocaleString(); // 更新完成时间
          // 刷新订单详情
          this.fetchOrderDetail();
        }).catch(() => {
          this.$message.info('已取消确认收货');
        });
      } catch (error) {
        console.error('确认收货出错:', error);
        this.$message.error('确认收货失败，请稍后重试');
      }
    },

    // 打印订单
    printOrder() {
      this.$message({
        message: '正在准备打印预览...',
        type: 'info'
      });

      // 创建一个临时的打印区域
      const printArea = document.createElement('div');
      printArea.className = 'print-only';
      printArea.style.display = 'none';

      // 设置打印内容
      const printContent = document.createElement('div');
      printContent.style.cssText = 'padding: 20px; font-family: Arial, sans-serif;';

      const title = document.createElement('h2');
      title.style.cssText = 'text-align: center; margin-bottom: 20px;';
      title.textContent = '订单详情';
      printContent.appendChild(title);

      const createOrderInfo = (label, value) => {
        const p = document.createElement('p');
        p.style.cssText = 'margin: 10px 0;';
        p.textContent = `${label}：${value}`;
        return p;
      };

      printContent.appendChild(createOrderInfo('订单编号', this.order.orderNo));
      printContent.appendChild(createOrderInfo('创建时间', this.order.createTime));
      printContent.appendChild(createOrderInfo('订单状态', this.getStatusText(this.order.status)));
      printContent.appendChild(createOrderInfo('商品名称', this.order.productName));
      printContent.appendChild(createOrderInfo('订单金额', `￥${this.order.totalAmount}`));

      if (this.order.payTime) {
        printContent.appendChild(createOrderInfo('支付时间', this.order.payTime));
      }
      if (this.order.completeTime) {
        printContent.appendChild(createOrderInfo('完成时间', this.order.completeTime));
      }

      printArea.appendChild(printContent);
      document.body.appendChild(printArea);

      // 添加打印样式
      const style = document.createElement('style');
      style.textContent = '@media print { body * { visibility: hidden; } .print-only, .print-only * { visibility: visible; } .print-only { position: absolute; left: 0; top: 0; width: 100%; } }';
      document.head.appendChild(style);

      // 执行打印
      setTimeout(() => {
        window.print();
        // 打印完成后移除临时元素
        document.body.removeChild(printArea);
        document.head.removeChild(style);
      }, 300);
    }
  }
};
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

.error-container .el-button {
  margin-top: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.order-header h2 {
  margin: 0;
  font-size: 20px;
}

.order-info-card, .product-card, .payment-card {
  margin-bottom: 20px;
}

.order-status {
  margin-bottom: 15px;
}

.order-info .info-item {
  margin-bottom: 10px;
  display: flex;
}

.info-item .label {
  color: #606266;
  width: 100px;
}

.info-item .value {
  color: #303133;
  flex: 1;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-details {
  flex: 1;
}

.product-details h3 {
  margin: 0 0 10px;
  font-size: 16px;
}

.price-info {
  display: flex;
  justify-content: space-between;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.payment-info .info-item.total {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.payment-info .info-item.total .value {
  font-size: 18px;
}

/* 支付对话框样式 */
.payment-dialog-content {
  padding: 20px 0;
}

.payment-methods {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30px;
}

.payment-method-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 15px 30px;
  border: 2px solid #EBEEF5;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.payment-method-item:hover {
  border-color: #409EFF;
}

.payment-method-item.active {
  border-color: #409EFF;
  background-color: #ECF5FF;
}

.payment-method-item i {
  font-size: 24px;
  margin-bottom: 8px;
  color: #409EFF;
}

.payment-method-item span {
  font-size: 14px;
  color: #606266;
}

.qr-code-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.qr-code {
  width: 200px;
  height: 200px;
  margin-bottom: 15px;
  border: 1px solid #EBEEF5;
  padding: 10px;
  border-radius: 4px;
}

.qr-code-tip {
  color: #909399;
  font-size: 14px;
  text-align: center;
}
</style>
